package com.ihunanren.common.spider;

import java.net.MalformedURLException;
import java.net.URL;

import com.google.common.base.Strings;

public class UrlHelper {

	public static String formatLink(String link) throws MalformedURLException{
		URL url = new URL(link);
		return formatLink(url);
	}
	
	public static String formatLink(URL url) throws MalformedURLException{
		StringBuilder sb = new StringBuilder();
		sb.append(url.getProtocol()).append("://").append(url.getHost());
		
		String path = url.getPath();
		if(path != null && path.lastIndexOf("/") != 0){
			sb.append(path).append("/");
		}else{
			sb.append(path);
		}
		if (! Strings.isNullOrEmpty(url.getQuery())) {
			sb.append("?").append(url.getQuery());
		}
		return sb.toString();
	}
}
